//
//  ConversationTableViewCell.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "ConversationTableViewCell.h"

//#import "GroupAvatarImage.h"

#import "BTMessageModel.h"
#import "TextMessageModel.h"
#import "VoiceMessageModel.h"
#import "ImageMessageModel.h"

@interface ConversationTableViewCell ()

@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;
@property(nonatomic,strong)UIImageView * ignoreImage;
//@property (nonatomic, strong) GroupAvatarImage *avatarView;


@end

@implementation ConversationTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [self.iconView configLayerWithBorderWidth:0 andWithCornerRadius:22 andWithBorderColor:[UIColor clearColor]];
    [self.tipsLabel configLayerWithBorderWidth:0 andWithCornerRadius:6 andWithBorderColor:[UIColor clearColor]];
    
    _nameLabel.textColor=KHEXCOLOR(kBlackColor);
    _contentLabel.textColor=KHEXCOLOR(@"#AFAFAF");
    _timeLabel.textColor=KHEXCOLOR(@"#CCCCCC");
    
    _ignoreImage=[[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth-35, 30, 20, 20)];
    _ignoreImage.image=[UIImage imageNamed:@"静音"];
    _ignoreImage.hidden=YES;
    [self addSubview:_ignoreImage];
//    _tipsContainerView.backgroundColor=KHEXCOLOR(@"#E94634");
//    _tipsContainerView.hidden=NO;
//    self.tipsContainerView.hidden = self.tipsLabel.hidden = YES;
    
//    _avatarView = [[GroupAvatarImage alloc] initWithFrame:self.iconView.bounds];
//    [self.iconView addSubview:_avatarView];

}

- (void)setMessage:(BTMessageModel *)message {
    _message = message;
    
    self.contentView.backgroundColor = message.top ? KHEXCOLOR(kGrayColor_e8) : [UIColor whiteColor];
    // 时间
    self.timeLabel.text = [NSDate dateStrFromCstampTime:message.timestamp  withDateFormat:@"MM-dd HH:mm"];
    // 未读消息数
    NSInteger unreadCount = message.unreadCount + message.offlineUnreadCount;
    
    if (unreadCount == 0 || message.searchKeywords.length > 0) {
         self.tipsLabel.hidden = YES;
    } else {
        if (message.chatType == ChatTypeSystem) {
            self.tipsLabel.hidden=YES;
        }else
        {
          self.tipsLabel.hidden=NO;
        }
        self.tipsLabel.backgroundColor = message.ignore ? KHEXCOLOR(@"c2c2c2") : KHEXCOLOR(@"#E94634");
        self.tipsLabel.hidden=message.ignore?YES:NO;
        self.ignoreImage.hidden=!self.tipsLabel.hidden;
        
        self.tipsLabel.text = unreadCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld", unreadCount];
    }
//     self.tipsLabel.backgroundColor=KHEXCOLOR(@"#E94634");
    if (message.chatType==ChatTypeFriend) { // 单聊
        // 头像与名称
        
        NSInteger friendId = [[message.keyid componentsSeparatedByString:@"_"] lastObject].integerValue;

       ContactModel * rmodel = [[UserDataBaseTool shareUserDataBaseTool]queryFriends:[NSString stringWithFormat:@"%ld", friendId]];
        self.nameLabel.text = rmodel.nickname;
        [self.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage, rmodel.head]] placeholderImage:kHeadPlaceholderImage];
        // 内容
        if (message.msgtype == MessageTypeText) {
            TextMessageModel *textModel = (TextMessageModel *)message;
            NSString *content = textModel.msg;
            if (message.searchKeywords) {
                self.contentLabel.attributedText = [self highlightText:message.searchKeywords inStr:content];
            } else {
                self.contentLabel.text = content;
            }
        } else if (message.msgtype == MessageTypeImage) {
            self.contentLabel.text = @"[图片]";
        } else if (message.msgtype == MessageTypeVoice) {
            self.contentLabel.text = @"[语音]";
        } else if (message.msgtype == MessageTypeRecall) {
            self.contentLabel.text = message.messageDirection == MessageDirectionSend ? @"你撤回了一条消息" : @"对方撤回了一条消息";
        }else
        {
            self.contentLabel.text = [NSString stringWithFormat:@"%@",message.msg];
        }
        if (message.type_id == SystemMessageAgreeAddFriend) {
            self.contentLabel.text = @"你们已成为好友，可以开始聊天啦";
        }

    } else if (message.chatType == ChatTypeGroup) { // 群聊
        // 头像与名称
        NSInteger groupId;
        if ([NSObject ldy_isEmpty:message.keyid]) {
            groupId = [message.gId integerValue];
        }else
        {
            groupId = [[message.keyid componentsSeparatedByString:@"_"] lastObject].integerValue;
        }
        ContactModel * rmodel = [[UserDataBaseTool shareUserDataBaseTool]queryGroup:[NSString stringWithFormat:@"%ld", groupId]];
        if (rmodel) {
            
            [self.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage, rmodel.groupHead]] placeholderImage:kHeadPlaceholderImage];
        }else
        {
            [self.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage, message.groupHead]] placeholderImage:kHeadPlaceholderImage];
        }

        if (![NSObject ldy_isEmpty:rmodel.groupName]) {
            self.nameLabel.text = rmodel.groupName;
        }else
        {
            if(![NSObject ldy_isEmpty:message.groupName])
            {
                self.nameLabel.text = message.groupName;
                
            }else
            {
                self.nameLabel.text = message.username;
                [self.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage, message.head]] placeholderImage:kHeadPlaceholderImage];
           }
        }
        if (message.msgtype == MessageTypeText) {
            TextMessageModel *textModel = (TextMessageModel *)message;
            BOOL isBlank = [NSObject ldy_isEmpty:textModel.content];
            NSString *content =  [NSString stringWithFormat:@"%@: %@", message.username, textModel.msg];
//            NSString *content = textModel.content;
            if (message.searchKeywords) {
                self.contentLabel.attributedText = [self highlightText:message.searchKeywords inStr:content];
            } else {
                NSArray<NSString *> *components = [content componentsSeparatedByString:kAtDividedSymbols];
                if (components.count >= 2) {
                    content = components[0];
                }
                self.contentLabel.text = content;
                if (isBlank) {
                    self.contentLabel.text = @"";
                }
            }
            self.contentLabel.text = content;

        } else if (message.msgtype == MessageTypeImage) {
//            self.contentLabel.text = [NSString stringWithFormat:@"%@: [图片]", groupMembername];
            self.contentLabel.text = @"[图片]";
        } else if (message.msgtype == MessageTypeVoice) {
//            self.contentLabel.text = [NSString stringWithFormat:@"%@: [语音]", groupMembername];
            self.contentLabel.text = @"[语音]";
        } else if (message.msgtype == MessageTypeRecall) {
            self.contentLabel.text = message.messageDirection == MessageDirectionSend ? @"你撤回了一条消息" : @"一条消息被撤回了";
        }else
        {
            self.contentLabel.text=[NSString stringWithFormat:@"%@",message.msg];
        }
//        else
//            if (message.messageType == MessageTypeAgreeJoinGroup) {
//            self.contentLabel.text = @"有新成员入群";
//        }
        if (message.type_id == SystemMessageAuditJoinGroup) {
            self.contentLabel.text =[NSString stringWithFormat:@"%@ 加入群聊",[LoginManager shareLoginManager].userModel.nickname];
        }
        if (message.type_id == SystemMessageAuditCreateGroup) {
             self.contentLabel.text = @"创建群聊成功，开始聊天吧";
        }
        // @赋值
        if (message.isAt) {
            if (message.messageDirection == MessageDirectionReceive) {
                NSString *text = message.content;
                NSArray<NSString *> *components = [text componentsSeparatedByString:kAtDividedSymbols];
                if (components.count < 2) {
                    if (self.contentLabel.attributedText) {
                        self.contentLabel.attributedText = [self highlightAtTips];
                    } else {
                        self.contentLabel.text = components[0];
                        self.contentLabel.textColor = [UIColor grayColor];
                    }
                    return;
                }
//                NSString *content = components[0];
                NSString *idsStr = components[1];
                __block BOOL isAtSelf = NO;
                if ([idsStr isEqualToString:kAtAllSymbols]) {
                    isAtSelf = YES;
                } else {
                    NSArray<NSString *> *ids = [idsStr componentsSeparatedByString:@","];
                    [ids enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        NSInteger uid = obj.integerValue;
                        if (uid == [LoginManager shareLoginManager].userModel.user_id.integerValue) {
                            
                            isAtSelf = YES;
                            *stop = YES;
                        }
                    }];
                }
                
                if (isAtSelf) {
                    self.contentLabel.attributedText = [self highlightAtTips];
                } else {
                    self.contentLabel.attributedText = nil;
                }
            }
        }
    } else if (message.chatType == ChatTypeSystem){ // 系统消息
        
        if (message.type_id == SystemMessageApplyCreateGroup|| message.type_id ==  SystemMessageAuditCreateGroup || message.type_id ==  SystemMessageDeleteGroup || message.type_id ==  SystemMessageApplyJoinGroup || message.type_id ==  SystemMessageAuditJoinGroup || message.type_id ==  SystemMessageRefusedJoinGroup ||   message.type_id ==  SystemMessageMemberExit ||  message.type_id == SystemMessageDeleteGroupMember ) {
            self.iconView.image=[UIImage imageNamed:@"群通知"];
            self.nameLabel.text=@"群通知";
            self.contentLabel.text=message.msg;
        }else if (message.type_id ==SystemMessagebill)
        {
            self.iconView.image=[UIImage imageNamed:@"账单通知"];
            self.nameLabel.text=@"账单通知";
            self.contentLabel.text=message.msg;

        }
//        if (message.type_id == SystemMessageAuditJoinGroup || message.type_id == SystemMessageAuditCreateGroup) {
//            self.nameLabel.text = @"群聊群聊";
//        }
    }
}

- (NSAttributedString *)highlightText:(NSString *)keyword inStr:(NSString *)str {
    NSRange range = [str rangeOfString:keyword];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
    if (range.length > 0) {
        [attrStr addAttribute:NSForegroundColorAttributeName value:KHEXCOLOR(kMainColor) range:range];
    } else {
        
    }
    return [[NSAttributedString alloc]initWithAttributedString:attrStr];
}

- (NSAttributedString *)highlightAtTips {
    NSString *str = @"[有人@我，请进入查收详情]······";
    NSString *keyword = @"[有人@我，请进入查收详情]";
    NSRange range = [str rangeOfString:keyword];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
    if (range.length > 0) {
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    } else {
        
    }
    return [[NSAttributedString alloc]initWithAttributedString:attrStr];
}


@end
